


using System;
using System.Data;
using System.Linq;
using System.Linq.Expressions;
using SubSonic.DataProviders;
using SubSonic.Extensions;
using SubSonic.Linq.Structure;
using SubSonic.Query;
using SubSonic.Schema;
using System.Data.Common;
using System.Collections.Generic;

namespace DataModel
{
    public partial class SUPNETDBDB : IQuerySurface
    {

        public IDataProvider DataProvider;
        public DbQueryProvider provider;
        
        public static IDataProvider DefaultDataProvider { get; set; }

        public bool TestMode
		{
            get
			{
                return DataProvider.ConnectionString.Equals("test", StringComparison.InvariantCultureIgnoreCase);
            }
        }

        public SUPNETDBDB() 
        {
            if (DefaultDataProvider == null) {
                DataProvider = ProviderFactory.GetProvider("supnetdb");
            }
            else {
                DataProvider = DefaultDataProvider;
            }
            Init();
        }

        public SUPNETDBDB(string connectionStringName)
        {
            DataProvider = ProviderFactory.GetProvider(connectionStringName);
            Init();
        }

		public SUPNETDBDB(string connectionString, string providerName)
        {
            DataProvider = ProviderFactory.GetProvider(connectionString,providerName);
            Init();
        }

		public ITable FindByPrimaryKey(string pkName)
        {
            return DataProvider.Schema.Tables.SingleOrDefault(x => x.PrimaryKey.Name.Equals(pkName, StringComparison.InvariantCultureIgnoreCase));
        }

        public Query<T> GetQuery<T>()
        {
            return new Query<T>(provider);
        }
        
        public ITable FindTable(string tableName)
        {
            return DataProvider.FindTable(tableName);
        }
               
        public IDataProvider Provider
        {
            get { return DataProvider; }
            set {DataProvider=value;}
        }
        
        public DbQueryProvider QueryProvider
        {
            get { return provider; }
        }
        
        BatchQuery _batch = null;
        public void Queue<T>(IQueryable<T> qry)
        {
            if (_batch == null)
                _batch = new BatchQuery(Provider, QueryProvider);
            _batch.Queue(qry);
        }

        public void Queue(ISqlQuery qry)
        {
            if (_batch == null)
                _batch = new BatchQuery(Provider, QueryProvider);
            _batch.Queue(qry);
        }

        public void ExecuteTransaction(IList<DbCommand> commands)
		{
            if(!TestMode)
			{
                using(var connection = commands[0].Connection)
				{
                   if (connection.State == ConnectionState.Closed)
                        connection.Open();
                   
                   using (var trans = connection.BeginTransaction()) 
				   {
                        foreach (var cmd in commands) 
						{
                            cmd.Transaction = trans;
                            cmd.Connection = connection;
                            cmd.ExecuteNonQuery();
                        }
                        trans.Commit();
                    }
                    connection.Close();
                }
            }
        }

        public IDataReader ExecuteBatch()
        {
            if (_batch == null)
                throw new InvalidOperationException("There's nothing in the queue");
            if(!TestMode)
                return _batch.ExecuteReader();
            return null;
        }
			
        public Query<D_Invoice> D_Invoice { get; set; }
        public Query<D_Reconciliation> D_Reconciliation { get; set; }
        public Query<D_ShopPO> D_ShopPO { get; set; }
        public Query<D_ShopRO> D_ShopRO { get; set; }
        public Query<D_SupplierPO> D_SupplierPO { get; set; }
        public Query<D_SupplierRO> D_SupplierRO { get; set; }
        public Query<M_Company> M_Company { get; set; }
        public Query<M_Dept> M_Dept { get; set; }
        public Query<M_Goods> M_Goods { get; set; }
        public Query<M_ReconciliationStatus> M_ReconciliationStatus { get; set; }
        public Query<M_Shop> M_Shop { get; set; }
        public Query<M_StatusCode> M_StatusCode { get; set; }
        public Query<M_Supplier> M_Supplier { get; set; }
        public Query<M_SysCode> M_SysCode { get; set; }
        public Query<R_ReconciliationAndOrder> R_ReconciliationAndOrder { get; set; }
        public Query<View_Reconciliation> View_Reconciliation { get; set; }
        public Query<View_SupplierPO> View_SupplierPO { get; set; }
        public Query<View_SupplierPOMaster> View_SupplierPOMaster { get; set; }
        public Query<View_SupplierRO> View_SupplierRO { get; set; }
        public Query<View_SupplierROMaster> View_SupplierROMaster { get; set; }

			

        #region ' Aggregates and SubSonic Queries '
        public Select SelectColumns(params string[] columns)
        {
            return new Select(DataProvider, columns);
        }

        public Select Select
        {
            get { return new Select(this.Provider); }
        }

        public Insert Insert
		{
            get { return new Insert(this.Provider); }
        }

        public Update<T> Update<T>() where T:new()
		{
            return new Update<T>(this.Provider);
        }

        public SqlQuery Delete<T>(Expression<Func<T,bool>> column) where T:new()
        {
            LambdaExpression lamda = column;
            SqlQuery result = new Delete<T>(this.Provider);
            result = result.From<T>();
            result.Constraints=lamda.ParseConstraints().ToList();
            return result;
        }

        public SqlQuery Max<T>(Expression<Func<T,object>> column)
        {
            LambdaExpression lamda = column;
            string colName = lamda.ParseObjectValue();
            string objectName = typeof(T).Name;
            string tableName = DataProvider.FindTable(objectName).Name;
            return new Select(DataProvider, new Aggregate(colName, AggregateFunction.Max)).From(tableName);
        }

        public SqlQuery Min<T>(Expression<Func<T,object>> column)
        {
            LambdaExpression lamda = column;
            string colName = lamda.ParseObjectValue();
            string objectName = typeof(T).Name;
            string tableName = this.Provider.FindTable(objectName).Name;
            return new Select(this.Provider, new Aggregate(colName, AggregateFunction.Min)).From(tableName);
        }

        public SqlQuery Sum<T>(Expression<Func<T,object>> column)
        {
            LambdaExpression lamda = column;
            string colName = lamda.ParseObjectValue();
            string objectName = typeof(T).Name;
            string tableName = this.Provider.FindTable(objectName).Name;
            return new Select(this.Provider, new Aggregate(colName, AggregateFunction.Sum)).From(tableName);
        }

        public SqlQuery Avg<T>(Expression<Func<T,object>> column)
        {
            LambdaExpression lamda = column;
            string colName = lamda.ParseObjectValue();
            string objectName = typeof(T).Name;
            string tableName = this.Provider.FindTable(objectName).Name;
            return new Select(this.Provider, new Aggregate(colName, AggregateFunction.Avg)).From(tableName);
        }

        public SqlQuery Count<T>(Expression<Func<T,object>> column)
        {
            LambdaExpression lamda = column;
            string colName = lamda.ParseObjectValue();
            string objectName = typeof(T).Name;
            string tableName = this.Provider.FindTable(objectName).Name;
            return new Select(this.Provider, new Aggregate(colName, AggregateFunction.Count)).From(tableName);
        }

        public SqlQuery Variance<T>(Expression<Func<T,object>> column)
        {
            LambdaExpression lamda = column;
            string colName = lamda.ParseObjectValue();
            string objectName = typeof(T).Name;
            string tableName = this.Provider.FindTable(objectName).Name;
            return new Select(this.Provider, new Aggregate(colName, AggregateFunction.Var)).From(tableName);
        }

        public SqlQuery StandardDeviation<T>(Expression<Func<T,object>> column)
        {
            LambdaExpression lamda = column;
            string colName = lamda.ParseObjectValue();
            string objectName = typeof(T).Name;
            string tableName = this.Provider.FindTable(objectName).Name;
            return new Select(this.Provider, new Aggregate(colName, AggregateFunction.StDev)).From(tableName);
        }

        #endregion

        void Init()
        {
            provider = new DbQueryProvider(this.Provider);

            #region ' Query Defs '
            D_Invoice = new Query<D_Invoice>(provider);
            D_Reconciliation = new Query<D_Reconciliation>(provider);
            D_ShopPO = new Query<D_ShopPO>(provider);
            D_ShopRO = new Query<D_ShopRO>(provider);
            D_SupplierPO = new Query<D_SupplierPO>(provider);
            D_SupplierRO = new Query<D_SupplierRO>(provider);
            M_Company = new Query<M_Company>(provider);
            M_Dept = new Query<M_Dept>(provider);
            M_Goods = new Query<M_Goods>(provider);
            M_ReconciliationStatus = new Query<M_ReconciliationStatus>(provider);
            M_Shop = new Query<M_Shop>(provider);
            M_StatusCode = new Query<M_StatusCode>(provider);
            M_Supplier = new Query<M_Supplier>(provider);
            M_SysCode = new Query<M_SysCode>(provider);
            R_ReconciliationAndOrder = new Query<R_ReconciliationAndOrder>(provider);
            View_Reconciliation = new Query<View_Reconciliation>(provider);
            View_SupplierPO = new Query<View_SupplierPO>(provider);
            View_SupplierPOMaster = new Query<View_SupplierPOMaster>(provider);
            View_SupplierRO = new Query<View_SupplierRO>(provider);
            View_SupplierROMaster = new Query<View_SupplierROMaster>(provider);
            #endregion


            #region ' Schemas '
        	if(DataProvider.Schema.Tables.Count == 0)
			{
            	DataProvider.Schema.Tables.Add(new D_InvoiceStructs(DataProvider));
            	DataProvider.Schema.Tables.Add(new D_ReconciliationStructs(DataProvider));
            	DataProvider.Schema.Tables.Add(new D_ShopPOStructs(DataProvider));
            	DataProvider.Schema.Tables.Add(new D_ShopROStructs(DataProvider));
            	DataProvider.Schema.Tables.Add(new D_SupplierPOStructs(DataProvider));
            	DataProvider.Schema.Tables.Add(new D_SupplierROStructs(DataProvider));
            	DataProvider.Schema.Tables.Add(new M_CompanyStructs(DataProvider));
            	DataProvider.Schema.Tables.Add(new M_DeptStructs(DataProvider));
            	DataProvider.Schema.Tables.Add(new M_GoodsStructs(DataProvider));
            	DataProvider.Schema.Tables.Add(new M_ReconciliationStatusStructs(DataProvider));
            	DataProvider.Schema.Tables.Add(new M_ShopStructs(DataProvider));
            	DataProvider.Schema.Tables.Add(new M_StatusCodeStructs(DataProvider));
            	DataProvider.Schema.Tables.Add(new M_SupplierStructs(DataProvider));
            	DataProvider.Schema.Tables.Add(new M_SysCodeStructs(DataProvider));
            	DataProvider.Schema.Tables.Add(new R_ReconciliationAndOrderStructs(DataProvider));
            	DataProvider.Schema.Tables.Add(new View_ReconciliationStructs(DataProvider));
            	DataProvider.Schema.Tables.Add(new View_SupplierPOStructs(DataProvider));
            	DataProvider.Schema.Tables.Add(new View_SupplierPOMasterStructs(DataProvider));
            	DataProvider.Schema.Tables.Add(new View_SupplierROStructs(DataProvider));
            	DataProvider.Schema.Tables.Add(new View_SupplierROMasterStructs(DataProvider));
            }
            #endregion
        }
        

        #region ' Helpers '
            
        internal static DateTime DateTimeNowTruncatedDownToSecond() {
            var now = DateTime.Now;
            return now.AddTicks(-now.Ticks % TimeSpan.TicksPerSecond);
        }

        #endregion

    }
}